<template>
  <div class="app-container">
  <div v-show="!showAdd.showcp">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="项目编号" prop="fNumber">
        <el-input
          v-model="queryParams.fNumber"
          placeholder="请输入项目编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="fName">
        <el-input
          v-model="queryParams.fName"
          placeholder="项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行政区" prop="fXzqqsdm">
        <!--        <el-input v-model="queryParams.fXzqqsdm" placeholder="请选择行政区" clearable size="small" @keyup.enter.native="handleQuery"/>-->
        <xzq-list ref="xzqlistCom"></xzq-list>
      </el-form-item>


      <el-form-item>
        <el-button class="left50" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="项目编号" align="center" prop="fNumber"/>
      <el-table-column label="项目名称" align="center" prop="fName"/>
      <el-table-column label="规划建设规模（万亩）" align="center" prop="fScaleArea"/>
      <el-table-column label="申报总投资（万元）" align="center" prop="fPlanTotal"/>
      <el-table-column label="行政区划" align="center" prop="fXzqmc"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleGetData(scope.row)"
          >详情
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-map-location"-->
<!--            @click="handleToMap(scope.row)"-->
<!--          >地图-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="wyicon-erweima"-->
<!--            @click="handleQRC(scope.row)"-->
<!--          >二维码-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="detailDialogOpen" width="85%">
      <his-pro-detail ref="detail" :pro-detail="currentPro"></his-pro-detail>
    </el-dialog>
    <el-dialog :title="dialogTitle" :visible.sync="mapDialogOpen" width="85%">
      <map-comp ref="mapComp" class="map-hight" :proFeatures="proFeatures"></map-comp>
    </el-dialog>
    <el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="qrcimgList" />
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
    <CreateProject v-if="showAdd.showcp" :showAdd="showAdd" :formData="formData" ></CreateProject>
  </div>
</template>

<script>
import { getGbzcb, listGbzcbcx } from '@/api/business/gbzcb'
import { getGbzQrcfromBM } from '@/api/gbznt/gbzCommon.js'
import {getCatalogQueryConfigListByIds} from "@/api/portal/catalog";
import XzqList from '@/components/Xzq/XzqList'
import hisProDetail from '@/views/business/gbzxm/hisProDetail'
import MapComp from '@/components/Map/mapComp'
import CreateProject from '@/views/business/gbzcb/createProject'
import { requestBaseUrl } from '@/utils/request'


export default {
  name: 'searchHiProject',
  components: {
    MapComp,
    hisProDetail,
    XzqList,
    CreateProject,
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  data() {
    return {
      showAdd: { showcp: false, readonly: false, tododeal: false },
      formData:{},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 待办表格数据
      projectList: [],
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      detailDialogOpen: false,
      //显示地图弹出层
      mapDialogOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fName: null,
        fNumber:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        xmbh: [
          { required: true, message: '项目编号不能为空', trigger: 'blur' }
        ],
        ztzys: [
          { type: 'number', message: '项目编号不能为空', trigger: 'blur' }
        ]
      },
      selectVal: '', // select框的绑定值
      selectName: '', // select框显示的name
      currentPro: null,//选择的某一个项目
      //目录树
      'projectLayerTreeData': [
        {
          name: 'gbzHistoryProject',
          label: '高标准历史项目',
          id: '31dd5d40-5461-4704-8bad-ad62456c88b1',
          type: 1
        }],
      analysisLayers: [],
      selectLayInformation: null,//选中的图层
      sqlStr: '',//查询语句
      proFeatures: [],
      imgViewerVisible:false,
      qrcimgList:[],
    }
  },
  props: {

    queryFieldNameXZQ: {
      type: String,
      default() {
        return 'f_xzqqsdm'
      }
    }
  },
  created() {
    this.getList()

    // this.queryXzqListAjax();
  },
  mounted() {
    this.queryServiceQueryDataAjax(this.projectLayerTreeData)
  },
  methods: {
    //跳转至一张图进行项目查询
    goToOneMap() {
      window.open(gConfig.spbtdir.yztFronturl+"inCoInterface");
    },
    //生成二维码
    handleQRC(row) {
      let that=this;
      this.currentPro = row
      let query = {
        message:gConfig.spbtdir.ruoyiFronturl+"gbzxmInfoQRC?uuid="+this.currentPro.uuid,
        name: this.currentPro.uuid
      }

      getGbzQrcfromBM(query).then(response => {
        let furl=requestBaseUrl+"gbzqrc/"+response.data;
        that.qrcimgList=[];
        that.qrcimgList.push(furl);
        that.imgViewerVisible=true;
      })
    },
    // 关闭查看器
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    /** 查询待办列表 */
    getList() {
      this.loading = true
      listGbzcbcx(this.queryParams).then(response1 => {
        let resHi=response1;
          this.projectList = resHi.rows
          this.total = resHi.total
          this.loading = false
      })
    },
    //获取
    handleGetData(row) {
      //  this.reset();
      this.showAdd.showcp = false
      const id = row.fId
      getGbzcb(id).then(response => {
        this.formData = response.data
        // this.formData.taskId
        this.showTable = false
        this.showAdd.readonly = true//不允许编辑
        this.showAdd.showcp = true
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        xmbh: null,
        xmmc: null,
        xmzgbm: null,
        xmsheng: null,
        xmshi: null,
        xmxian: null,
        gbzntjsyear: null,
        yswjmc: null,
        yswjwh: null,
        ysrq: null,
        jsddys: null,
        xmqgdzbys: null,
        gbzntgdzb: null,
        ztzys: null,
        shtzys: null,
        zytzys: null,
        dftzys: null,
        jsgmys: null,
        gbzntjcmjys: null,
        xzgdmjys: null,
        xzgxjsggmj: null,
        jcgnzntzldj: null,
        beizhu: null,
        fXzqdm: null,
        fXzqqsmc: null,
        nksgm: null,
        id: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      if (this.$refs.xzqlistCom.selectData) {
        this.queryParams.fXzqdm = this.$refs.xzqlistCom.selectData.xzqcode
      }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      //下面ztzysmin和ztzysmax这两个参数不知道为什么清空不了。手动清空
     // this.queryParams.gbzntjcmjysmin = null
     // this.queryParams.gbzntjcmjysmax = null
      this.queryParams.fName = null
      this.queryParams.fNumber = null
      this.queryParams.fXzqdm = null
      this.$refs.xzqlistCom.clearSelectXzq()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加待办'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDemo(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改待办'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDemo(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDemo(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除待办编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDemo(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportDemo(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },

    handleToMap(row) {
      this.dialogTitle = row.xmmc
      this.queryFeaturesByRegionsAjax(row)

    },
    /*通过图层id，向后台请求图层信息*/
    queryServiceQueryDataAjax(dataIds) {
      let that = this
      that.analysisLayers = []
      let serviceids = []
      dataIds.forEach(function(layer, i) {
        if (layer.hasOwnProperty('id')) {
          serviceids.push(layer.id)
        }
      })
      let seridsStrTemp = JSON.stringify(serviceids)
      let seridsStr = seridsStrTemp.replace('[', '')
      seridsStr = seridsStr.replace(']', '')
      seridsStr = seridsStr.replace('"', '')
      getCatalogQueryConfigListByIds({
        "serviceIds": seridsStr.trim()
      }).then((res) => {
        let queryCatalog = res.data
        if (queryCatalog.queryData.length > 0) {
          for (let i in queryCatalog.queryData) {
            let obj = queryCatalog.queryData[i]
            let name = obj.f_name
            let id = obj.f_catalogid
            let dataUrl = obj.f_url //数据服务地址
            let analysisUrl = obj.f_analysisurl //分析服务地址
            let datasourceNames = [{ 'name': obj.f_datasource, 'value': obj.f_datasource }]
            let datasetNames = [{ 'name': obj.f_dataset, 'value': obj.f_dataset }]
            let fieldData = JSON.parse(obj.f_fieldconfig)
            if (dataUrl != null && dataUrl != '') {
              let layerJson = {
                'name': name,
                'id': id,
                'dataUrl': dataUrl,
                'analysisUrl': analysisUrl,
                'datasourceName': datasourceNames[0].name,
                'datasetName': datasetNames[0].name,
                'fieldData': fieldData
              }
              that.analysisLayers.push(layerJson)
            }
          }
        }
        that.selectLayInformation = that.analysisLayers[0] //初始化绑定
      }).catch((error) => {
        // catch 指请求出错的处理
        console.log(error)
      });
    },

    //在超图里，SQL语句查询level
    queryFeaturesByRegionsAjax: function(currentPro) {
      //sql查询
      let that = this
      that.sqlStr = 'xmbh=\'' + currentPro['xmbh'] + '\''
      that.proFeatures = []
      //  that.attribute.fromIndex = param.fromIndex;
      //  that.attribute.toIndex = param.toIndex;
      let attributeFilter = null
      //2022年7月8日 LQ 先不用权限控制。直接用哪个编码来。
      //if (this.sqlConfig.mapRegion.f_s != 1) {
        //  attributeFilter = that.queryFieldNameXZQ + " LIKE '" + that.sqlConfig.mapRegion.f_regioncode + "%'";
     // }
      if (attributeFilter != null) {
        attributeFilter = that.sqlStr + ' AND ' + attributeFilter
      } else {
        attributeFilter = that.sqlStr
      }
      let sqlParam = new SuperMap.GetFeaturesBySQLParameters({
        queryParameter: {
          name: that.selectLayInformation.datasetName + '&' + that.selectLayInformation.datasourceName,
          //attributeFilter: that.sqlStr,
          attributeFilter: attributeFilter
        },
        datasetNames: [that.selectLayInformation.datasourceName + ':' + that.selectLayInformation.datasetName],
        // fromIndex: 0, //分页查询参数用来返回查询结果的数量 定义查询结果的最小索引号
        //toIndex: 1000000, //分页查询参数用来返回查询结果的数量 定义查询结果的最大索引号
        fromIndex: 0,
        toIndex: -1,
        maxFeatures: -1//不加上这一句，就只返回最多1000条结果
      })
      new ol.supermap.FeatureService(that.selectLayInformation.dataUrl).getFeaturesBySQL(sqlParam, function(serviceResult) {
        // that.attribute.totalCount = serviceResult.result.totalCount;
        let features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features)
        that.proFeatures = features
        that.mapDialogOpen = true
        that.$nextTick(() => {
          //  alert(this.$refs.mapComp.toString())
          that.$refs.mapComp.AddFeaturesToOverSource(features)
        })

        if (features.length > 0) {
          //why20211018转换投影
        //  let defaultPrjCode = that.sqlConfig.mapRegion.prjcode
          // let mapPrjCode = that.sqlConfig.map.getView().getProjection().getCode();
          // if (defaultPrjCode != mapPrjCode) {
          //   for (let i = 0; i < features.length; i++) {
          //     features[i].getGeometry().transform(that.sqlConfig.mapRegion.prjcode, that.sqlConfig.map.getView().getProjection().getCode());
          //   }
          // }
          // let params=[features,that.selectLayInformation.fieldData,that.sqlConfig.map,that.selectLayInformation["id"],
          //   that.attribute.totalCount,that.attribute.fromIndex,that.attribute.toIndex,prj,false];
          // Bus.$emit('setMapBottom',"300px");
          // Bus.$emit('intCatalogAttributeTable',params);
        }
      })
    }
  },
  beforeDestroy() {        //收尾操作，销毁
    //Bus.$off('getWorkflowTodoList')  //$off解绑当前组件所用到的事件
  }
}
</script>

<style scoped>
.page-explain{
  margin: 2px 15px;
  color: #48af6e;
}

.map-hight {
  height: 85vh;
}

.ztzys {
  width: 285px;
  margin-right: 21px !important;
  display: inline-flex !important;
}

::v-deep .el-dialog__body {
  padding: 10px 10px;
}

::v-deep .el-dialog__headerbtn {
  top: 5px;
  right: 5px;
  font-size: 26px;
}

::v-deep .el-dialog__header {
  padding: 10px 0px 0px 10px;
}

::v-deep .el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 185px;
}

::v-deep .el-input__inner {
  height: 35px;
  line-height: 35px;
}

::v-deep .el-input__prefix, .el-input__suffix {
  top: -3px;
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: rgba(173, 199, 133, 0.62) !important;
}

::v-deep .el-input__inner {
  margin-bottom: 8px
}

::v-deep .el-form-item {
  margin-bottom: 8px;
}

::v-deep .el-input {
  width: 90%;
}

::v-deep .el-form-item__label {
  line-height: 30px;
  min-width: 100px;
}

::v-deep .el-form-item__content {
  line-height: 25px;
}

::v-deep .el-form--inline .el-form-item {
  margin-right: 0px;
}

.left50 {
  margin-left: 30px;
}
</style>
